﻿using YXChatFormClient.Component.Message;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Alert_Form.Component.Alert;
using YXChatFormClient.Dtos.Account;
using YXChatFormClient.Dtos.Buddy;
using YXChatFormClient.Global;
using YXChatFormClient.UserControls;
using YXChatFormClient.Utility;
using YXChatFormClient.Utility.HubHelp;
using YXChatFormClient.Dtos;
using YXChatFormClient.Dtos.ChatRecord;

namespace YXChatFormClient
{
    public partial class FrmIndex : Form
    {
        private readonly HttpHelper _http;
        public FrmIndex()
        {
            _http = new HttpHelper();
            InitializeComponent();
            //设置控件样式
            SetStyle(
                ControlStyles.AllPaintingInWmPaint | //不闪烁
                ControlStyles.OptimizedDoubleBuffer //支持双缓存
                , true);
            this.label1.Text = JSONHelper.ReadJSON<string>("IndexTitle");
            GlobalAccountInfo.AvatarChanged += GlobalAccountInfo_AvatarChanged;
            InitAccountInfo();
            AllControlBindSelectEvent();
            ChatService.ReceiveAddBuddyNotify(ReceiveAddBuddyResult);
            ChatService.ReceiveSendMessage(ReceiveSendMessageHandler);
        }
        
        #region 用户头像
        /// <summary>
        /// 初始化用户头像
        /// </summary>
        public void InitAccountInfo()
        {
            //头像
            var avatarUrl = GlobalAccountInfo.Account.Avatar;
            if (!avatarUrl.IsNullOrWhiteSpace())
            {
                picAvatar.ImageLocation = ImageHelper.GetServerImage(avatarUrl);
            }
        }
        /// <summary>
        /// 修改头像时触发
        /// </summary>
        private void GlobalAccountInfo_AvatarChanged()
        {
            InitAccountInfo();
        }
        /// <summary>
        /// 点击头像弹出个人信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picAvatar_Click(object sender, EventArgs e)
        {
            picAvatar.Select();
            using (MessageBoxFrom frm = new MessageBoxFrom())
            {
                UC_AccountCenter accountCenter = new UC_AccountCenter();
                frm.ShowMessage(accountCenter);
            }
        }

        #endregion

        #region Common
        //自定义拖动窗体
        [DllImport("user32.dll", EntryPoint = "ReleaseCapture")]
        private static extern void ReleaseCapture();

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        private static extern void SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

        #region 边框阴影
        private const int CS_DropShadow = 0x00020000;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ClassStyle |= CS_DropShadow;
                return cp;
            }
        }
        #endregion

        #region Panel重绘
        private void panelMenu_Paint(object sender, PaintEventArgs e)
        {
            PaintHelper.PaintBorder(e, panelMenu.ClientRectangle, Color.White,
                Color.White, Color.FromArgb(214, 214, 214), Color.White);
        }

        private void panelMenuItems_Paint(object sender, PaintEventArgs e)
        {
            PaintHelper.PaintBorder(e, panelMenuItems.ClientRectangle, Color.White,
                Color.White, Color.FromArgb(214, 214, 214), Color.White);
        }

        private void panelConentLayoutHeader_Paint(object sender, PaintEventArgs e)
        {
            PaintHelper.PaintBorder(e, panelConentLayoutHeader.ClientRectangle, Color.White,
                Color.White, Color.White, Color.FromArgb(214, 214, 214));
        }

        private void panelSearch_Paint(object sender, PaintEventArgs e)
        {
            PaintHelper.PaintBorder(e, panelSearch.ClientRectangle, Color.White,
                Color.White, Color.FromArgb(214, 214, 214), Color.FromArgb(214, 214, 214));
        }
        #endregion

        #region 功能按钮
        #region 关闭按钮
        private void picClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void picClose_MouseMove(object sender, MouseEventArgs e)
        {
            picClose.BackColor = Color.FromArgb(250, 81, 81);
            picClose.ImageLocation = ImageHelper.GetStaticImage("close_active.png");
        }

        private void picClose_MouseLeave(object sender, EventArgs e)
        {
            picClose.BackColor = Color.White;
            picClose.ImageLocation = ImageHelper.GetStaticImage("close.png");
        }


        #endregion

        #region 最小化按钮
        private void picMinimize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void picMinimize_MouseMove(object sender, MouseEventArgs e)
        {
            picMinimize.BackColor = Color.FromArgb(229, 229, 229);
        }

        private void picMinimize_MouseLeave(object sender, EventArgs e)
        {
            picMinimize.BackColor = Color.White;
        }
        #endregion

        #region 最大化按钮
        private void picMaximize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.panelLayoutContent.Dock = DockStyle.Fill;
                this.WindowState = FormWindowState.Maximized;
            }
            else
            {
                this.panelLayoutContent.Dock = DockStyle.Right;
                this.WindowState = FormWindowState.Normal;
            }
        }
        private void picMaximize_MouseLeave(object sender, EventArgs e)
        {
            picMaximize.BackColor = Color.White;
        }
        private void picMaximize_MouseMove(object sender, MouseEventArgs e)
        {
            picMaximize.BackColor = Color.FromArgb(229, 229, 229);
        }
        #endregion
        #endregion

        #region 头部
        /// <summary>
        /// 头部拖动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panelConentLayoutHeader_MouseDown(object sender, MouseEventArgs e)
        {
            this.panelConentLayoutHeader.Select();
            ReleaseCapture();
            SendMessage(this.Handle, 0x112, 0xf012, 0);
        }

        #endregion

        /// <summary>
        /// 所有控件点击事件加上获取焦点
        /// </summary>
        private void AllControlBindSelectEvent()
        {
            foreach (Control control in this.Controls)
            {
                control.Click += (object sender, EventArgs e) =>
                {
                    control.Select();
                };
            }
        }

        #endregion

        /// <summary>
        /// 添加用户控件，用户内容切换
        /// </summary>
        /// <param name="control"></param>
        private void AddControlsToContentPanel(Control control)
        {
            control.Dock = DockStyle.Fill;
            panelContent.Controls.Clear();
            panelContent.Controls.Add(control);
        }

        #region 初始化容器
        public UC_ChatsContainer ChatContainer;
        public UC_BuddysContainer BuddyContainer;
        public UC_MessageContainer MessageContainer;
        public UC_NoAction NoAction => new UC_NoAction();
        /// <summary>
        /// 初始化菜单
        /// </summary>
        private async void InitMenuPanelControls()
        {
            // 获取用户所有的聊天记录的最后一条
            var chats = await _http.GetAsync<List<ChatRecordAccountDto>>($"{Api.GetChatRecordAll}/{GlobalAccountInfo.Account.AccountNumber}");
            // 初始页面展示聊天menu
            ChatContainer = new UC_ChatsContainer
            {
                Dock = DockStyle.Fill,
                ChatRecordAccounts = chats
            };
            ChatContainer.ChatClick += ChatContainer_ChatClick;
            panelMenuItems.Controls.Add(ChatContainer);
            // 初始化时，添加NoAction控件
            AddControlsToContentPanel(NoAction);
        }

        /// <summary>
        /// 聊天item点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="ChatRecord"></param>
        private async void ChatContainer_ChatClick(object sender, EventArgs e, ChatRecordAccountDto ChatRecord)
        {
            this.lbHeaderDesc.Text = ChatRecord.Account.NickName;
            var selfNumber = GlobalAccountInfo.Account.AccountNumber;
            var buddyNumber = ChatRecord.Account.AccountNumber;
            // 获取用于与指定好友的所有聊天记录
            var chatRecord = await _http.GetAsync<ChatRecordAccountDto>($"{Api.GetChatRecord}/{selfNumber}/{buddyNumber}");
            MessageContainer = new UC_MessageContainer()
            {
                Dock = DockStyle.Fill,
                ChatRecordAccountDto = chatRecord
            };
            AddControlsToContentPanel(MessageContainer);
        }

        /// <summary>
        /// 好友item点击事件
        /// </summary>
        /// <param name="buddyAccountOutput"></param>
        private void BuddyContainer_BuddyClick(BuddyAccountOutput buddyAccountOutput)
        {
            this.lbHeaderDesc.Text = buddyAccountOutput.Account.NickName;
            UC_BuddyInfo uCBuddyInfo = new UC_BuddyInfo
            {
                BuddyAccountOutput = buddyAccountOutput,
                Dock = DockStyle.Fill
            };
            uCBuddyInfo.GoToSendMsgClick += UC_BuddyInfo_GoToSendMsgClick;
            panelContent.Controls.Clear();
            panelContent.Controls.Add(uCBuddyInfo);
        }

        private async void UC_BuddyInfo_GoToSendMsgClick(BuddyAccountOutput buddyAccountOutput)
        {
            picChat.Select();
            string selfNumber = GlobalAccountInfo.Account.AccountNumber;
            string buddyNumber = buddyAccountOutput.Account.AccountNumber;
            // 获取和好友的聊天记录
            var chatRecordAccount = await _http.GetAsync<ChatRecordAccountDto>($"{Api.GetChatRecord}/{selfNumber}/{buddyNumber}");
            this.lbHeaderDesc.Text = buddyAccountOutput.Account.NickName;
            // 重新渲染聊天内容窗口
            MessageContainer = new UC_MessageContainer()
            {
                Dock = DockStyle.Fill,
                ChatRecordAccountDto = chatRecordAccount
            };
            // 聊天列表追加
            if (!chatRecordAccount.ChatRecord.Any())
            {
                if (ChatContainer.ChatRecordAccounts.All(n => n.Account.AccountNumber != chatRecordAccount.Account.AccountNumber))
                {
                    ChatContainer.ChatRecordAccounts.Add(chatRecordAccount);
                }
            }
            // 重新渲染聊天menu容器
            ChatContainer = new UC_ChatsContainer
            {
                Dock = DockStyle.Fill,
                ChatRecordAccounts = ChatContainer.ChatRecordAccounts
            };
            ChatContainer.ChatClick += ChatContainer_ChatClick;
            panelMenuItems.Controls.Clear();
            panelMenuItems.Controls.Add(ChatContainer);
            AddControlsToContentPanel(MessageContainer);
        }

        /// <summary>
        /// 新的好友点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BuddyContainer_UserControlNewBuddyClicked(object sender, EventArgs e)
        {
            this.lbHeaderDesc.Text = "新的朋友";
            this.panelContent.Controls.Clear();
            var result = await _http.GetAsync<List<BuddyAccountOutput>>($"{Api.GetNewBuddys}/{GlobalAccountInfo.Account.AccountNumber}");

            foreach (var item in result)
            {
                UC_NewBuddyNotify newBuddyNotify = new UC_NewBuddyNotify()
                {
                    Dock = DockStyle.Top,
                    BuddyAccountOutput = item
                };
                newBuddyNotify.AgreeBuddyClick += BuddyContainer_UserControlNewBuddyClicked;
                this.panelContent.Controls.Add(newBuddyNotify);
            }
        }

        #endregion

        #region 聊天menu
        private async void picChat_Click(object sender, EventArgs e)
        {
            lbHeaderDesc.Text = string.Empty;
            var chats = await _http.GetAsync<List<ChatRecordAccountDto>>($"{Api.GetChatRecordAll}/{GlobalAccountInfo.Account.AccountNumber}");
            AddControlsToContentPanel(NoAction);
            picChat.Select();
            ChatContainer = new UC_ChatsContainer
            {
                Dock = DockStyle.Fill,
                ChatRecordAccounts = chats
            };
            ChatContainer.ChatClick += ChatContainer_ChatClick;
            panelMenuItems.Controls.Clear();
            panelMenuItems.Controls.Add(ChatContainer);
        }
        private void picChat_MouseMove(object sender, MouseEventArgs e)
        {
            picChat.ImageLocation = ImageHelper.GetStaticImage("chat_active.png");
        }

        private void picChat_MouseLeave(object sender, EventArgs e)
        {
            picChat.ImageLocation = ImageHelper.GetStaticImage("chat.png");
        }
        #endregion

        #region 好友menu
        private void picPeople_Click(object sender, EventArgs e)
        {
            lbHeaderDesc.Text = string.Empty;
            AddControlsToContentPanel(NoAction);
            BuddyContainer = new UC_BuddysContainer() { Dock = DockStyle.Fill };
            BuddyContainer.UserControlNewBuddyClicked += BuddyContainer_UserControlNewBuddyClicked;
            BuddyContainer.BuddyClick += BuddyContainer_BuddyClick;
            panelMenuItems.Controls.Clear();
            panelMenuItems.Controls.Add(BuddyContainer);
            BuddyContainer.Select();
        }
        private void picPeople_MouseMove(object sender, MouseEventArgs e)
        {
            picPeople.ImageLocation = ImageHelper.GetStaticImage("people_active.png");
        }

        private void picPeople_MouseLeave(object sender, EventArgs e)
        {
            picPeople.ImageLocation = ImageHelper.GetStaticImage("people.png");
        }
        #endregion

        /// <summary>
        /// 添加好友按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picAdd_Click(object sender, EventArgs e)
        {
            picAdd.Select();
            using (MessageBoxFrom frm = new MessageBoxFrom())
            {
                UC_SearchBuddy searchBuddy = new UC_SearchBuddy();
                frm.ShowMessage(searchBuddy);
            }
        }

        #region Chat
        private void ReceiveAddBuddyResult(AccountDto account)
        {
            Invoke((MethodInvoker)delegate ()
            {
                AlertForm.ShowAlert($"{account.NickName}  申请您为好友", AlertType.Info, 10 * 60,
                    direction: ShowDirection.BottomRight);
            });
        }
        protected void ReceiveSendMessageHandler(MessageNotifyDto messageNotify)
        {
            Invoke((MethodInvoker)delegate ()
            {
                AlertForm.ShowAlert($"{messageNotify.Account.NickName} 给您发了一条信息",
                    AlertType.Info, 3,
                    direction: ShowDirection.BottomRight);

                var menuItems = Controls.Find("panelMenuItems", true)[0];
                var chatContainer = menuItems.Controls[0] as UC_ChatsContainer;
                List<UC_ChatItem> chats = new List<UC_ChatItem>();
                if (chatContainer != null)
                {
                    // 找出所有聊天item控件
                    foreach (Control control in chatContainer.Controls)
                    {
                        if (control is UC_ChatItem chatItem)
                        {
                            chats.Add(chatItem);
                        }
                    }

                    // 如果接收到的消息的发送者在聊天列表中已经存在 则true
                    var receiveChatItem = chats.FirstOrDefault(n =>
                        n.ChatRecordAccount.Account.AccountNumber == messageNotify.Account.AccountNumber);
                    // 存在 则修改数据
                    if (receiveChatItem != null)
                    {
                        receiveChatItem.ChatRecordAccount.ChatRecord[0] = messageNotify.ChatRecordDto;
                        receiveChatItem.Refresh();
                    }
                    // 不存在 则添加聊天item控件
                    else
                    {
                        UC_ChatItem chatItem = new UC_ChatItem()
                        {
                            Dock = DockStyle.Top,
                            ChatRecordAccount = new ChatRecordAccountDto()
                            {
                                Account = messageNotify.Account,
                                ChatRecord = new List<ChatRecordDto>()
                                {
                                    messageNotify.ChatRecordDto
                                }
                            }
                        };
                        chatItem.ChatClick += chatContainer.ChatItem_ChatClick;
                        chatContainer.Controls.Add(chatItem);

                        // 重新渲染聊天menu容器
                        menuItems.Controls.Clear();
                        menuItems.Controls.Add(chatContainer);
                    }

                }
            });
        }

        #endregion

        private void FrmIndex_Load(object sender, EventArgs e)
        {
            InitMenuPanelControls();
        }
    }
}
